using AutoMapper;
using Core.SimpleTemp.Application.common;
using Core.SimpleTemp.Common;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Repositories;
using Core.Toolkit.Common;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Core.Toolkit.Core.Application;
using Core.Toolkit.Message;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.SimpleTemp.Application
{
    [AutoDi()]
    public class PX_PlanService : BaseAppService<PX_PlanDto, PX_Plan, PX_PlanRepository>
    {
        readonly ExcelHelp _excelHelp;
        IMessage _message;
        readonly BusinessOptions _webAppOptions;
        PX_ExamRepository _examrepository;
        public PX_PlanService(PX_PlanRepository repository, PX_ExamRepository examrepository, ExcelHelp excelHelp, IOptionsMonitor<BusinessOptions> webAppOptions, IMessage message) : base(repository)
        {
            _excelHelp = excelHelp;
            _message = message;
            _examrepository = examrepository;
            _webAppOptions = webAppOptions.CurrentValue;

        }



        private LoadPageOffsetModelAuto<PX_Plan, PX_PlanDto>
            GetLoadPageOffsetMode(PagingModel<PX_PlanDto>
                pagingQueryModel)
        {
            var loadPageOffsetModel = this.GetLoadPageOffsetModelAuto(pagingQueryModel);
            var baseQuery = _repository.QueryBase().AsNoTracking();
            loadPageOffsetModel.QueryWhere = this.CreateQRList()
     //.Add("TrainingMatrix", "=")
     .Add("Nameoftrainingplan", "in");
            //.Add("HeadofTraining", "=")
            //.Add("Trainingbudget", "=")
            //.Add("TrainingBeginTime", "=")
            //.Add("TrainingEndTime", "=")
            //.Add("Trainingvenues", "=")
            //.Add("Trainer", "=")
            //.Add("Trainingmethods", "=")
            //.Add("trainingcourse", "=")
            //.Add("Trainingcontent", "=")
            //.Add("state", "=")
            //.Add("CreateFactory", "=")
            //.Add("CreateDept", "=")
            //.Add("UpdateDept", "=");


            loadPageOffsetModel.BasqQuery = baseQuery;
            loadPageOffsetModel.Order = orderModel => orderModel.CreateTime;
            //loadPageOffsetModel.Selector = model => new PX_Plan()
            //{
            //    Id = model.Id,
            //    TrainingMatrix = model.TrainingMatrix,
            //    Nameoftrainingplan = model.Nameoftrainingplan,
            //    HeadofTraining = model.HeadofTraining,
            //    Trainingbudget = model.Trainingbudget,
            //    TrainingBeginTime = model.TrainingBeginTime,
            //    TrainingEndTime = model.TrainingEndTime,
            //    Trainingvenues = model.Trainingvenues,
            //    Trainer = model.Trainer,
            //    Trainingmethods = model.Trainingmethods,
            //    trainingcourse = model.trainingcourse,
            //    Trainingcontent = model.Trainingcontent,
            //    state = model.state,
            //    CreateFactory = model.CreateFactory,
            //    CreateDept = model.CreateDept,
            //    UpdateDept = model.UpdateDept,
            //};
            return loadPageOffsetModel;
        }

        private LoadPageOffsetModelAuto<PX_Plan, PX_PlanDto>
           PCGetLoadPageOffsetMode(PagingModel<PX_PlanDto>
               pagingQueryModel)
        {
            var loadPageOffsetModel = this.GetLoadPageOffsetModelAuto(pagingQueryModel);
            var baseQuery = _repository.QueryBase().AsNoTracking().Include(x=>x.PX_Exam);
            loadPageOffsetModel.QueryWhere = this.CreateQRList()

           //.Add("TrainingMatrix", "=")
           // .Add("Nameoftrainingplan", "in");
           //.Add("HeadofTraining", "=")
           //.Add("Trainingbudget", "=")
           .Add("TrainingBeginTime", ">=", DateTimeFormat.getTime(pagingQueryModel.Model.TrainingBeginTime, "b"))
     .Add("TrainingBeginTime", "<", DateTimeFormat.getTime(pagingQueryModel.Model.TrainingEndTime, "e"))
            //.Add("Trainingvenues", "=")
            //.Add("Trainer", "=")
            //.Add("Trainingmethods", "=")
            //.Add("trainingcourse", "=")
            //.Add("Trainingcontent", "=")
            //.Add("state", "=")
            .Add("CreateFactory", "=");
            //.Add("CreateDept", "=")
            //.Add("UpdateDept", "=");


            loadPageOffsetModel.BasqQuery = baseQuery;
            loadPageOffsetModel.OrderList = new List<OrderModel>()
            {
                new OrderModel(){
                     IsDesc=true,
                      PropertyName="TrainingBeginTime"
                }
            };

            loadPageOffsetModel.Selector = model => new PX_Plan()
            {
                Id = model.Id,
                //TrainingMatrix = model.TrainingMatrix,
                //Nameoftrainingplan = model.Nameoftrainingplan,
                //HeadofTraining = model.HeadofTraining,
                Trainingbudget = model.Trainingbudget,
                TrainingBeginTime = model.TrainingBeginTime,
                //TrainingEndTime = model.TrainingEndTime,
                //Trainingvenues = model.Trainingvenues,
                Mark04 = _repository._dbContext.SysUserInfor.Where(x => x.SysUserID == model.Trainer).FirstOrDefault().Name,
                Trainingmethods = model.Trainingmethods,
                Mark03 = _repository._dbContext.PX_Course.Where(x => x.Id == model.trainingcourse).FirstOrDefault().CoursewareName,
                Trainingcontent = model.Trainingcontent,
                State = model.State,
                Target = model.Target,
                Mark01 = model.PX_PlanUser.Count.ToString(),
                MasteryLevel = model.MasteryLevel,
                PX_PlanUser = model.PX_PlanUser,
                PX_Exam=model.PX_Exam

            };
            return loadPageOffsetModel;
        }



        public async Task<PX_PlanForGetDto> PCGet(Guid id)
        {
            var baseQuery = _repository.QueryBase().AsNoTracking().Include(u => u.PX_Exam).Include(u => u.PX_PlanUser).Include(u => u.PX_Course).Include(x=>x.PX_SignDetail);
            var userEntity = await base.GetAsync(id, baseQuery);
            var userDto = Mapper.Map<PX_PlanForGetDto>(userEntity);

            userDto.UserIdList = new List<Guid?>();
            userDto.Mark05 = _repository._dbContext.SysUserInfor.Where(x => x.SysUserID == userDto.Trainer).FirstOrDefault().Name;

            

            foreach (PX_PlanUser pnp in userDto.PX_PlanUser.Where(x => x.IsDeleted == false))
            {
                userDto.UserIdList.Add(pnp.PersonID);
                userDto.Mark06 += _repository._dbContext.SysUserInfor.Where(x => x.SysUserID == pnp.PersonID).FirstOrDefault().Name + ',';
                pnp.Mark01 = _repository._dbContext.SysUserInfor.Where(x => x.SysUserID == pnp.PersonID).FirstOrDefault().Name;
                var SysUserDepartmentDuty = _repository._dbContext.SysUserDepartmentDuty.Where(y => y.SysUserInforID == pnp.PersonID)
                .FirstOrDefault();
                if (SysUserDepartmentDuty != null)
                {
                    pnp.Mark02 = _repository._dbContext.SysDepartment
                    .Where(x => x.Id == SysUserDepartmentDuty
                    .SysDepartmentID).FirstOrDefault().Name;
                }
                pnp.Mark03 = _repository._dbContext.SysDataDic.Where(x => x.Category == "通过状态" && x.Key == pnp.IsQualified).FirstOrDefault().Value;
                pnp.Mark04 = _repository._dbContext.SysDataDic.Where(x => x.Category == "签到状态" && x.Key == pnp.IsSign).FirstOrDefault().Value;

            }

            userDto.Mark06 = userDto.Mark06.TrimEnd(',');

            userDto.pdnum = _repository._dbContext.PX_Questions.Where(ur => ur.trainingcourse == userDto.trainingcourse && ur.QuestionManagementType == "2").ToList().Count;
            userDto.duoxnum = _repository._dbContext.PX_Questions.Where(ur => ur.trainingcourse == userDto.trainingcourse && ur.QuestionManagementType == "1").ToList().Count;
            userDto.danxnum = _repository._dbContext.PX_Questions.Where(ur => ur.trainingcourse == userDto.trainingcourse && ur.QuestionManagementType == "0").ToList().Count;

            return userDto;
        }


        public async Task<IPageModel<PX_PlanDto>> GetList(PagingModel<PX_PlanDto>
            pagingQueryModel)
        {
            var loadPageOffsetModel = GetLoadPageOffsetMode(pagingQueryModel);
            return await base.LoadPageOffsetAsync(loadPageOffsetModel);
        }

        public async Task<IPageModel<PX_PlanDto>> PCGetList(PagingModel<PX_PlanDto>
            pagingQueryModel)
        {
            var loadPageOffsetModel = PCGetLoadPageOffsetMode(pagingQueryModel);
            return await base.LoadPageOffsetAsync(loadPageOffsetModel);
        }

        public async Task<IPageModel<PX_PlanDto>> WDPX(PagingModel<PX_PlanDto>
            pagingQueryModel,Guid id)
        {
            var loadPageOffsetModel = GetLoadPageOffsetModelWDPX(pagingQueryModel,id);
            return await base.LoadPageOffsetAsync(loadPageOffsetModel);
        }

        public async Task<string>
            ExportWDPX(PagingModel<PX_PlanDto>
                pagingQueryModel,Guid id)
        {
            var loadPageOffsetModel = GetLoadPageOffsetModelWDPX(pagingQueryModel,id);
            var DataList = await this.ExportDataAsync(loadPageOffsetModel);
            var excelData = DataList.Select(model => new
            {
                model.TrainingBeginTime,
                TrainingBeginTime_title = "培训时间",
                model.Mark01,
                Mark01_title = "培训课程",
                model.Target,
                Target_title = "培训目标",
                model.Trainingcontent,
                Trainingcontent_title = "培训内容",
                model.Mark02,
                Mark02_title = "培训方式",
                model.Mark03,
                Mark03_title = "考核方式",
                model.Mark07,
                Mark07_title = "培训计划状态",
                model.Mark04,
                Mark04_title = "状态",
                model.Mark09,
                Mark09_title = "已培训时长",
                model.Mark10,
                Mark10_title = "需培训时长",
                model.Mark05,
                Mark05_title = "得分",
            }).ToList();
            return _excelHelp.Create(excelData);
        }


        public LoadPageOffsetModelAuto<PX_Plan, PX_PlanDto> GetLoadPageOffsetModelWDPX(PagingModel<PX_PlanDto> pagingQueryModel, Guid id)
        {

            var loadPageOffsetModel = this.GetLoadPageOffsetModelAuto(pagingQueryModel);
            var baseQuery = _repository.QueryBase().AsNoTracking().Where( a=>a.PX_PlanUser.Where(c => c.PersonID == id).Any()
            && (a.State == "1" || a.State == "2" || a.State == "3" || a.State == "4"));

            loadPageOffsetModel.QueryWhere = this.CreateQRList()
        .Add("TrainingBeginTime", ">=", DateTimeFormat.getTime(pagingQueryModel.Model.TrainingBeginTime, "b"))
        .Add("TrainingBeginTime", "<", DateTimeFormat.getTime(pagingQueryModel.Model.TrainingEndTime, "e"));
            loadPageOffsetModel.BasqQuery = baseQuery;
            //loadPageOffsetModel.Order = orderModel => orderModel.CreateTime;
            loadPageOffsetModel.OrderList = new List<OrderModel>()
            {
                new OrderModel(){
                     IsDesc=true,
                      PropertyName="TrainingBeginTime"
                }
            };
            loadPageOffsetModel.Selector = model => new PX_Plan()
            {
                Id = model.PX_PlanUser.Where(x => x.PersonID == id).FirstOrDefault().Id,
                TrainingBeginTime = model.TrainingBeginTime,
                Mark01 = model.PX_Course.CoursewareName,
                Target = model.Target,
                Trainingcontent = model.Trainingcontent,
                //培训方式
                Mark02 = _repository._dbContext.SysDataDic.Where(x => x.Category == "w64" && x.Key == model.Trainingmethods).FirstOrDefault().Value,
                //考核方式
                Mark03 = _repository._dbContext.SysDataDic.Where(x => x.Category == "w64" && x.Key == model.PX_Exam.Examinationmethods).FirstOrDefault().Value,
                //是否通过
                Mark04 = _repository._dbContext.SysDataDic.Where(x => x.Category == "通过状态" && x.Key == model.PX_PlanUser.Where(y => y.PersonID == id).FirstOrDefault().IsQualified).FirstOrDefault().Value,
                //得分
                Mark05 = model.PX_PlanUser.Where(x => x.PersonID == id).FirstOrDefault().Score.ToString(),
                //在线时长是否足够
                Mark06 = model.PX_Course.Learningtime <= model.PX_PlanUser.Where(x => x.PersonID == id).FirstOrDefault().CourseHours ? "是" : "否",
                //培训状态
                Mark07 = _repository._dbContext.SysDataDic.Where(x => x.Category == "培训状态" && x.Key == model.State).FirstOrDefault().Value,
                //对应课件 html地址
                Mark08 = _repository._dbContext.SysFile.Where(x => x.Id == model.PX_Course.HtmlID).FirstOrDefault().FilePath,
                //已培训时长
                Mark09 = model.Trainingmethods=="1"?"无要求":  model.PX_PlanUser.Where(x => x.PersonID == id).FirstOrDefault().CourseHours.ToString(),
                //需培训时长
                Mark10 = model.PX_Course.Learningtime.ToString()

            };

            return loadPageOffsetModel;
        }

        public async Task<IPageModel<PX_PlanDto>> KSJK(PagingModel<PX_PlanDto> pagingQueryModel, Guid id)
        {
            var loadPageOffsetModel = GetLoadPageOffsetModelKSJK(pagingQueryModel, id);


            return await base.LoadPageOffsetAsync(loadPageOffsetModel);
        }
        public LoadPageOffsetModelAuto<PX_Plan, PX_PlanDto> GetLoadPageOffsetModelKSJK(PagingModel<PX_PlanDto> pagingQueryModel, Guid id)
        {

            var loadPageOffsetModel = this.GetLoadPageOffsetModelAuto(pagingQueryModel);
            var baseQuery = _repository.QueryBase().AsNoTracking().Where(a =>
            (a.PX_Exam.Examinationmethods == "0"))
            //&& (a.Status == "3" || a.Status == "4" || a.Status == "6"))
            ;

            loadPageOffsetModel.QueryWhere = this.CreateQRList().Add("PX_Course.CoursewareName", "in", pagingQueryModel.Model.Nameoftrainingplan)
                .Add("CreateFactory", "=");
            loadPageOffsetModel.BasqQuery = baseQuery;
            loadPageOffsetModel.Order = orderModel => orderModel.PX_Exam.Status;
            loadPageOffsetModel.Selector = model => new PX_Plan()
            {
                Id = model.Id,
                Nameoftrainingplan = model.PX_Course.CoursewareName,
                //考试模式
                //Mark01 = _repository._dbContext.SysDataDic.Where(x => x.Category == "006" && x.Key == model.PX_Exam.Examinationmethods).FirstOrDefault().Value,
                TrainingBeginTime = model.TrainingBeginTime,
                Mark05 = _repository._dbContext.SysDataDic.Where(x => x.Category == "培训状态" && x.Key == model.State).FirstOrDefault().Value,

                //合格分数
                Mark02 = model.PX_Exam.Qualificationscore.ToString(),
                //考生人数
                Mark03 = _repository._dbContext.PX_PlanUser.Where(x => x.PlanID == model.Id).Count().ToString(),
                //合格人数
                Mark04 = model.PX_PlanUser.Where(x => x.IsQualified == "1" && x.PlanID == model.Id).Count().ToString(),
                

            };

            return loadPageOffsetModel;
        }

        public async Task<string> ExportForKSJK(PagingModel<PX_PlanDto> pagingQueryModel, Guid id)
        {
            var loadPageOffsetModel = GetLoadPageOffsetModelKSJK(pagingQueryModel, id);

            var DataList = await this.ExportDataAsync(loadPageOffsetModel);
            var excelData = DataList.Select(model => new
            {
               
                model.Nameoftrainingplan,
                Nameoftrainingplan_title = "试卷名称",
                model.TrainingBeginTime,
                TrainingBeginTime_title = "开始时间",
                model.Mark05,
                Mark05_title = "状态",
                model.Mark03,
                Mark03_title = "考生人数",
                model.Mark04,
                Mark04_title = "合格人数",
                model.Mark02,
                Mark02_title = "合格分数",



            }).ToList();

            return _excelHelp.Create(excelData);
        }


        public async Task<string>
            Export(PagingModel<PX_PlanDto>
                pagingQueryModel)
        {
            var loadPageOffsetModel = PCGetLoadPageOffsetMode(pagingQueryModel);
            var DataList = await this.ExportDataAsync(loadPageOffsetModel);

            DataList.ForEach(dto =>
            {
                var str = "";
                dto.PX_PlanUser.ToList().ForEach(a =>
                {
                    str += _repository._dbContext.SysUserInfor.Where(x => x.SysUserID == a.PersonID).FirstOrDefault().Name + ",";
                });
                str = str.TrimEnd(',');

                dto.Mark02 = str;

            });


            var excelData = DataList.Select(model => new
            {

                model.Mark03,
                Mark03_title = "培训课程",
                model.Target,
                Target_title = "培训目标",
                model.Mark02,
                Mark02_title = "目标人群",
                model.TrainingBeginTime,
                TrainingBeginTime_title = "培训时间",
                model.Mark01,
                Mark01_title = "参加人数",
                model.Trainingbudget,
                Trainingbudget_title = "预算",
                model.Mark04,
                Mark04_title = "培训讲师",
                model.MasteryLevelText,
                MasteryLevelText_title = "掌握程度",
                model.TrainingmethodsText,
                TrainingmethodsText_title = "培训方式",
                model.Trainingcontent,
                Trainingcontent_title = "培训内容",
                model.StateText,
                StateText_title = "状态",

            }).ToList();




            return _excelHelp.Create(excelData);
        }



        public string Notice(Guid id)
        {
            var obj = _repository._dbContext.PX_Plan.Where(x => x.Id == id).Include(x => x.PX_Course).Include(x=>x.PX_Exam).Include(x=>x.PX_PlanUser).FirstOrDefault();

            if (obj.TrainingBeginTime < DateTime.Now.Date)
            {
                return "失败";
            }
            //如果开始日期是今天 直接状态已开始
            if (obj.TrainingBeginTime.Value.Year == DateTime.Now.Year
                && obj.TrainingBeginTime.Value.Month == DateTime.Now.Month
                 && obj.TrainingBeginTime.Value.Day == DateTime.Now.Day)
            {
                //直接变为 已开始   有可能需要处理其他内容
                obj.State = "2";
                obj.PX_PlanUser.ToList().ForEach(y =>
                {
                    //判断培训是否是线下培训 线上考试 如果是 生成考试信息
                    if (obj.PX_Exam.Examinationmethods == "0")
                    {
                        PX_ExamUser eu = new PX_ExamUser();
                        eu.ExamId = obj.PX_ExamId;
                        eu.Examinationmethods = obj.PX_Exam.Examinationmethods;
                        eu.Examinationscore = 0;
                        eu.Examinationstatus = "0";
                        eu.Fullmarks = obj.PX_Exam.Fullmarks.Value;
                        eu.Numberofexaminations = 0;
                        eu.PersonID = y.PersonID;
                        eu.PX_PlanId = obj.Id;
                        eu.Qualificationscore = obj.PX_Exam.Qualificationscore.Value;
                        eu.Whethertoremindleaders = "0";
                        eu.IsQualified = "0";

                        _repository._dbContext.PX_ExamUser.Add(eu);
                    }

                });

            }
            else
            {
                obj.State = "1";
            }

            _repository._dbContext.SaveChanges();




            //发送消息
            var l = _repository._dbContext.PX_PlanUser.Where(x => x.PlanID == id).ToList();
            List<Toolkit.Message.Model.MessageModel> messlist = new List<Toolkit.Message.Model.MessageModel>();
            foreach (var PX_PlanNoticePerson in l)
            {
                Toolkit.Message.Model.MessageModel mess = new Toolkit.Message.Model.MessageModel();
                mess.FromUser = obj.CreateUser;
                mess.ToUser = PX_PlanNoticePerson.PersonID;
                mess.SendTime = DateTime.Now;
                mess.Ttitle = "培训通知";
                mess.Content = obj.PX_Course.CoursewareName + "培训于" + obj.TrainingBeginTime + "举行，请准时参与！";
                mess.BusiType = "PX_Plan";
                mess.BusiId = obj.Id;
                messlist.Add(mess);
            }
            _message.SendMessage(messlist);
            return "成功";
        }


        public string WCPX(Guid id)
        {
            var obj = _repository._dbContext.PX_Plan.Where(x => x.Id == id).Include(x => x.PX_Course).FirstOrDefault();

            obj.State = "4";
            _repository._dbContext.SaveChanges();


            return "成功";
        }


        public async Task SCPXJH(Guid factory)
        {
            //获取所有培训
            var mlist = await _repository._dbContext.PX_Matrix.Where(x => x.IsDeleted == false&&x.CreateFactory== factory).ToListAsync();

            List<Guid> courselist = new List<Guid>();
            List<PX_Plan> planlist = new List<PX_Plan>();
            //找出上次执行时间的年份 加 频率 =今年的
            foreach (PX_Matrix m in mlist)
            {
                if (m.LastComTime.Year + Convert.ToInt32(m.TrainTime) == DateTime.Now.Year)
                {
                    
                    
                    //生成记录
                    PX_Plan p = new PX_Plan();
                    List<Guid> userlist = new List<Guid>();
                    p.PX_PlanUser = new List<PX_PlanUser>();
                    p.PX_Exam = new PX_Exam();
                    p.State = "0";
                    p.Year = DateTime.Now.Year.ToString();
                    if (courselist.Contains(m.trainingcourse.Value))
                    {
                        //如果已经处理过该课程逻辑 continue  保证每个课程最多只生成一个计划
                        continue;
                    }
                    courselist.Add(m.trainingcourse.Value);
                    p.trainingcourse = m.trainingcourse;
                    //查找 该课程涉及的所有符合条件矩阵 再找 职务 再找 用户 
                    var matrixlist = await _repository._dbContext.PX_Matrix.Where(x => x.trainingcourse == m.trainingcourse
                    && m.LastComTime.Year + Convert.ToInt32(m.TrainTime) == DateTime.Now.Year).ToListAsync();
                    foreach (PX_Matrix pm in matrixlist)
                    {
                        var dutylist = await _repository._dbContext.SysDuty.Where(x => x.Id == pm.post).ToListAsync();
                        foreach (SysDuty s in dutylist)
                        {
                            var myulist = await _repository._dbContext.SysUserDepartmentDuty.Where(x => x.SysDutyID == s.Id).ToListAsync();
                            foreach (SysUserDepartmentDuty sudd in myulist)
                            {
                                PX_PlanUser user = new PX_PlanUser();
                                user.PersonID = sudd.SysUserInforID;
                                user.Score = 0;
                                user.IsSign = "0";
                                user.IsQualified = "0";
                                //已存在的人员
                                if (!userlist.Contains(sudd.SysUserInforID.Value))
                                {
                                    userlist.Add(sudd.SysUserInforID.Value);
                                    p.PX_PlanUser.Add(user);
                                }
                            }
                        }
                    }
                    p.Trainer = _repository._dbContext.PX_CourseTeacher.Where(x => x.trainingcourse == p.trainingcourse).FirstOrDefault().Teacher;


                    //方式默认线下
                    p.Trainingmethods = "1";
                    p.PX_Exam.Examinationmethods = "1";
                    p.PX_Exam.Fullmarks = 0;
                    p.PX_Exam.Qualificationscore = 0;
                    p.PX_Exam.SingleNumber = 0;
                    p.PX_Exam.SingleScore = 0;
                    p.PX_Exam.MultipleNumber = 0;
                    p.PX_Exam.MultipleScore = 0;
                    p.PX_Exam.JudgmentNumber = 0;
                    p.PX_Exam.JudgmentScore = 0;
                    p.CreateFactory = factory;
                    planlist.Add(p);
                }
            }

            await _repository._dbContext.PX_Plan.AddRangeAsync(planlist);
            await _repository.SaveAsync();

        }

        public async Task<bool> XinDeSaveAsync(PX_PlanUserDto dto)
        {
            PX_PlanUser pX_PlanUser = Mapper.Map<PX_PlanUser>(dto);
            var model = await _repository._dbContext.PX_PlanUser.Where(a => a.PlanID == dto.PlanID && a.PersonID == dto.PersonID).FirstOrDefaultAsync();
            if (model == null)
                await _repository._dbContext.PX_PlanUser.AddAsync(pX_PlanUser);
            else
            {
                //学习心得
                model.Experience = dto.Experience;
                //工作建议
                model.Advice = dto.Advice;
                //内容摘要
                model.Content = dto.Content;
            }
            await _repository._dbContext.SaveChangesAsync();
            return true;
        }

        public async Task<PX_PlanUser> GetPX_PlanUserAsync(PX_PlanUserDto dto)
        {
            return await _repository._dbContext.PX_PlanUser.Where(a => a.PlanID == dto.PlanID && a.PersonID == dto.PersonID).FirstOrDefaultAsync();
        }


        public async Task<PX_PlanUser> TotalizerMinute(PX_PlanUserDto dto)
        {
            var entity = await _repository._dbContext.PX_PlanUser.Where(a => a.PlanID == dto.PlanID && a.PersonID == dto.PersonID).FirstOrDefaultAsync();
            if (entity == null)
                _repository._dbContext.PX_PlanUser.Add(new PX_PlanUser()
                {
                    PlanID = dto.PlanID,
                    PersonID = dto.PersonID
                });
            await _repository._dbContext.SaveChangesAsync();
            entity = await _repository._dbContext.PX_PlanUser.Where(a => a.PlanID == dto.PlanID && a.PersonID == dto.PersonID).FirstOrDefaultAsync();

            if (entity.CourseHours == null)
                entity.CourseHours = 1;
            else
                entity.CourseHours++;
            await _repository._dbContext.SaveChangesAsync();

            return entity;
        }


        public async Task<Object> GetCourse(Guid id)
        {
            //课程 找到 矩阵 找到 岗位 找到人
            var lpm = await _repository._dbContext.PX_Course.Where(x => x.Id == id).Include(x => x.PX_CourseTeacher).FirstOrDefaultAsync();

            List<Guid> userlist = new List<Guid>();


            var matrixlist = await _repository._dbContext.PX_Matrix.Where(x => x.trainingcourse == id).ToListAsync();
            foreach (PX_Matrix m in matrixlist)
            {
                var dutylist = await _repository._dbContext.SysDuty.Where(x => x.Id == m.post).ToListAsync();
                foreach (SysDuty s in dutylist)
                {
                    var myulist = await _repository._dbContext.SysUserDuty.Where(x => x.SysDutyID == s.Id).ToListAsync();
                    foreach (SysUserDuty sudd in myulist)
                    {
                        userlist.Add(sudd.SysUserId);
                    }
                }
            }


            var result = new
            {
                trainingcourse = lpm.Id,
                pdnum = _repository._dbContext.PX_Questions.Where(ur => ur.trainingcourse == lpm.Id && ur.QuestionManagementType == "2").ToList().Count,
                duoxnum = _repository._dbContext.PX_Questions.Where(ur => ur.trainingcourse == lpm.Id && ur.QuestionManagementType == "1").ToList().Count,
                danxnum = _repository._dbContext.PX_Questions.Where(ur => ur.trainingcourse == lpm.Id && ur.QuestionManagementType == "0").ToList().Count,
                courseAttachment = lpm.CourseAttachment,
                attachmentName = lpm.AttachmentName,
                userlist = userlist,
                trainer = lpm.PX_CourseTeacher.Teacher

            };

            return result;
        }

        public override async Task<PX_PlanDto> InsertAsync(PX_PlanDto dto, bool autoSave = true)
        {
            dto.PX_Exam.Status = "0";
            var userDto = await base.InsertAsync(dto, false);
            if (dto.UserIdList != null)
            {
                foreach (var item in dto.UserIdList)
                {
                    _repository._dbContext.PX_PlanUser.Add(new PX_PlanUser
                    {
                        PersonID = item,
                        PlanID = userDto.Id,
                        IsQualified = "0",
                        IsSign="0",
                        Score=0
                        
                    });
                }



            }


            await _repository.SaveAsync();
            return userDto;
        }

        public override async Task<PX_PlanDto> UpdateAsync(PX_PlanDto dto, bool autoSave = true, List<string> noUpdateProperties = null)
        {
            dto.PX_Exam.Status = "0";
            var userDto = await base.UpdateAsync(dto, false, new List<string>() { nameof(dto.PX_PlanUser), nameof(dto.PX_Exam) });
            var delList = _repository._dbContext.PX_PlanUser.Where(ur => ur.PlanID == dto.Id);

            await _examrepository.UpdateAsync(Mapper.Map<PX_Exam>(dto.PX_Exam), false, null);


            _repository._dbContext.PX_PlanUser.RemoveRange(delList);


            if (dto.UserIdList != null)
            {
                foreach (var item in dto.UserIdList)
                {
                    _repository._dbContext.PX_PlanUser.Add(new PX_PlanUser
                    {
                        PersonID = item,
                        PlanID = userDto.Id
                    });
                }

            }

            await _repository.SaveAsync();
            return dto;
        }



        public async Task<Object> DealPlan()
        {

            List<Toolkit.Message.Model.MessageModel> messlist = new List<Toolkit.Message.Model.MessageModel>();

            //只有培训状态 没有考试状态了
            //已开始 2 变为 已结束 3
            var pxwclist = await _repository._dbContext.PX_Plan.Where
                (x => x.IsDeleted == false && x.TrainingEndTime < DateTime.Now.Date && x.State == "2").Include(x => x.PX_PlanUser).ToListAsync();
            pxwclist.ForEach(x =>
            {
                x.State = "3";
                x.PX_PlanUser.ToList().ForEach(y =>
                {
                    Toolkit.Message.Model.MessageModel mess = new Toolkit.Message.Model.MessageModel();
                    mess.FromUser = x.CreateUser;
                    mess.ToUser = y.PersonID;
                    mess.SendTime = DateTime.Now;
                    mess.Ttitle = "培训结束提醒";
                    mess.Content = x.PX_Course.CoursewareName + "培训于" + x.TrainingBeginTime.Value.ToString("yyyy-MM-dd") + "开始,请前往查看考试结果！";
                    mess.BusiType = "PX_PlanUserJS";
                    mess.BusiId = y.Id;
                    messlist.Add(mess);
                }
                );
            });

            //已通知 1 变为 已开始 2


            var pxkslist = await _repository._dbContext.PX_Plan.Where(x => x.IsDeleted == false &&
            DateTime.Parse(x.TrainingBeginTime.Value.ToString("yyyy-MM-dd")) <=
            DateTime.Parse(DateTime.Now.Date.ToString("yyyy-MM-dd")) && x.State == "1").Include(x => x.PX_PlanUser).Include(x => x.PX_Exam).ToListAsync();
            pxkslist.ForEach(x =>
            {
                x.State = "2";
                x.PX_PlanUser.ToList().ForEach(y =>
                {
                    //判断培训是否是线下培训 线上考试 如果是 生成考试信息
                    if ( x.PX_Exam.Examinationmethods=="0") {
                        PX_ExamUser eu = new PX_ExamUser();
                        eu.ExamId = x.PX_ExamId;
                        eu.Examinationmethods = x.PX_Exam.Examinationmethods;
                        eu.Examinationscore = 0;
                        eu.Examinationstatus = "0";
                        eu.Fullmarks = x.PX_Exam.Fullmarks.Value;
                        eu.Numberofexaminations = 0;
                        eu.PersonID = y.PersonID;
                        eu.PX_PlanId = x.Id;
                        eu.Qualificationscore = x.PX_Exam.Qualificationscore.Value;
                        eu.Whethertoremindleaders = "0";
                        eu.IsQualified = "0";

                        _repository._dbContext.PX_ExamUser.Add(eu);
                    }


                    Toolkit.Message.Model.MessageModel mess = new Toolkit.Message.Model.MessageModel();
                    mess.FromUser = x.CreateUser;
                    mess.ToUser = y.PersonID;
                    mess.SendTime = DateTime.Now;
                    mess.Ttitle = "培训开始提醒";
                    mess.Content = x.PX_Course.CoursewareName + "培训于" + x.TrainingBeginTime.Value.ToString("yyyy-MM-dd") + "[今日]开始,请准时参与！";
                    mess.BusiType = "PX_PlanUserKS";
                    mess.BusiId = y.Id;
                    messlist.Add(mess);

                }
                );
            });


            //提前 n天 提醒 负责人
            var l = await _repository._dbContext.PX_Plan.Where(x => x.IsDeleted == false && x.Mark07 != "已发" && x.TrainingBeginTime.Value.ToString("yyyy-MM-dd")
            == DateTime.Now.AddDays(_webAppOptions.BeforeDay).ToString("yyyy-MM-dd")).Include(x => x.PX_Course).ToListAsync();

            foreach (var _PX_Plan in l)
            {
                _PX_Plan.Mark07 = "已发";
                Toolkit.Message.Model.MessageModel mess = new Toolkit.Message.Model.MessageModel();
                mess.FromUser = Guid.Empty;
                mess.ToUser = _PX_Plan.CreateUser;
                mess.SendTime = DateTime.Now;
                mess.Ttitle = "培训计划提醒";
                mess.Content = _PX_Plan.PX_Course.CoursewareName + "培训计划于" + _PX_Plan.TrainingBeginTime.Value.ToString("yyyy-MM-dd") + "举行，请及时填写培训相关信息,及时发送通知！";
                mess.BusiType = "PX_PlanCreateUser";
                mess.BusiId = _PX_Plan.Id;
                messlist.Add(mess);
            }
            _message.SendMessage(messlist);
            return await _repository.SaveAsync();
        }

    }

}
